<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :default-selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="titleBar">
            <img class="logo" src="../assets/logo.png" />
            <div class="title">余答答</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <div v-if="loginUserStore.loginUser.id">
        <a-dropdown>
          <a-dropdown>
            <a-avatar :image-url="loginUserStore.loginUser?.userAvatar">
            </a-avatar>
            {{ loginUserStore.loginUser.userName ?? "无名" }}
            <template #content>
              <a-doption @click="logout">退出登录</a-doption>
            </template>
          </a-dropdown>
        </a-dropdown>
      </div>
      <div v-else>
        <a-button type="primary" href="/user/login">登录</a-button>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { ref } from "vue";
import { useLoginUserStore } from "@/store/userStore";
import checkAccess from "@/access/checkAccess";
import myAxios from "@/request";
import { Message } from "@arco-design/web-vue";

const loginUserStore = useLoginUserStore();

const router = useRouter();
// 当前选中的菜单项
const selectedKeys = ref(["/"]);
// 路由跳转时，自动更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

// 展示在菜单栏的路由数组
const visibleRoutes = routes.filter((item) => {
  if (item.meta?.hideInMenu) {
    return false;
  }
  // 根据全栈过滤菜单
  if (!checkAccess(loginUserStore.loginUser, item.meta?.access as string)) {
    return false;
  }
  return true;
});

// 点击菜单跳转到对应页面
const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};

// 登出方法
const logout = async () => {
  try {
    // 发送请求到服务器端点以登出
    await myAxios.post("/api/user/logout");
    // 清除用户信息
    loginUserStore.setLoginUser({ userName: "未登录" });
    // 重定向到首页
    await router.push("/");
    Message.success("登出成功，请重新登录");
  } catch (error) {
    console.error("登出失败:", error);
    Message.error("登出失败");
  }
};
</script>

<style scoped>
#globalHeader {
}

.titleBar {
  display: flex;
  align-items: center;
}

.title {
  margin-left: 16px;
  color: black;
}

.logo {
  height: 48px;
}

.arco-dropdown-open .arco-icon-down {
  transform: rotate(180deg);
}
</style>
